package controllers

import (
	"mime/multipart"
	"net/http"
	"strconv"

	"my-go-project/config"
	"my-go-project/model"
	"my-go-project/utils/token"

	"github.com/gin-gonic/gin"
)

type UserWithRelation struct {
	UserID       int
	Email        string
	UName        string
	Contact      string
	ContactType  string
	ProfilePhoto string
	Credit       float64
	FansNum      int
	IdolNum      int
	IfSubscribe  int
}

func GetUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	selfID, _ := token.ExtractTokenID(c)

	flag, _ := model.IfFollowed(id, int(selfID))
	var ifSubscribe int
	if int(selfID) == id {
		ifSubscribe = 0
	} else if flag {
		ifSubscribe = 1
	} else {
		ifSubscribe = 2
	}

	user, err := model.GetUserByID(id)
	userInfo := UserWithRelation{
		UserID:       user.UserID,
		Email:        user.Email,
		UName:        user.UName,
		Contact:      user.Contact,
		ContactType:  user.ContactType,
		ProfilePhoto: user.ProfilePhoto,
		Credit:       user.Credit,
		FansNum:      user.FansNum,
		IdolNum:      user.IdolNum,
		IfSubscribe:  ifSubscribe,
	}

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, userInfo)
}

type UserInfo struct {
	UName        string                `json:"UName"`
	Password     string                `json:"Password"`
	ProfilePhoto *multipart.FileHeader `json:"ProfilePhoto"`
	Contact      string                `json:"Contact"`
	ContactType  string                `json:"ContactType"`
}

func PostUser(c *gin.Context) {
	var userInfo UserInfo

	if err := c.ShouldBind(&userInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID, _ := token.ExtractTokenID(c)
	user := model.User{
		UName:       userInfo.UName,
		Password:    userInfo.Password,
		Contact:     userInfo.Contact,
		ContactType: userInfo.ContactType,
	}

	if userInfo.ProfilePhoto.Filename != "" {
		path := config.AppConfig.File.Path + strconv.Itoa(int(userID)) + "/ProfilePhoto.png"
		err := c.SaveUploadedFile(userInfo.ProfilePhoto, config.AppConfig.File.AbsolutePath+path)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save the file"})
			return
		}

		user.ProfilePhoto = path
	}
	user.UserID = int(userID)
	_, err := user.UpdateUser()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "modify success"})
}
